<?php
/**
 * Created by PhpStorm.
 * User: 盛茂国
 * Tel: 18394333958
 * Date: 2020/6/2
 * Time: 10:31
 */
namespace app\admin\controller;

use app\admin\model\Admin;
use app\admin\model\AuthGroup;
use app\admin\model\AuthGroupAccess;
use app\common\controller\Backend;
use fast\Random;
use fast\Tree;
use think\Validate;

/**
 * 设计师的增删改查  作者  盛茂国 tel:18394333958
 * Class Designer
 * @package app\admin\controller
 */



class Designer extends Backend
{
    protected $model = null;
    protected $childrenGroupIds = [];
    protected $childrenAdminIds = [];

    public function _initialize()
    {
        parent::_initialize();
        $this->model = model('Admin');

        $this->childrenAdminIds = $this->auth->getChildrenAdminIds(true);
        $this->childrenGroupIds = $this->auth->getChildrenGroupIds(true);

        $groupList = collection(AuthGroup::where('id', 'in', $this->childrenGroupIds)->select())->toArray();

        Tree::instance()->init($groupList);
        $groupdata = [];
        if ($this->auth->isSuperAdmin()) {
            $result = Tree::instance()->getTreeList(Tree::instance()->getTreeArray(0));
            foreach ($result as $k => $v) {
                $groupdata[$v['id']] = $v['name'];
            }
        } else {
            $result = [];
            $groups = $this->auth->getGroups();
            foreach ($groups as $m => $n) {
                $childlist = Tree::instance()->getTreeList(Tree::instance()->getTreeArray($n['id']));
                $temp = [];
                foreach ($childlist as $k => $v) {
                    $temp[$v['id']] = $v['name'];
                }
                $result[__($n['name'])] = $temp;
            }
            $groupdata = $result;
        }

        $this->view->assign('groupdata', $groupdata);
        $this->assignconfig("admin", ['id' => $this->auth->id]);
    }

    protected $noNeedLogin = [];

    protected $noNeedRight = ['*'];
    /**
     * 布局模板
     * @var string
     */
    protected $layout = 'default';
    /**
     * 权限控制类
     * @var Auth
     */
    protected $auth = null;


    /**
     * 查看
     */
    public function index()
    {
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            $factoryid=$this->auth->id;
            $where['factoryid']=$factoryid;
            $total = $this->model
                ->where($where)
                //->where('id', 'in', $this->childrenAdminIds)
                ->order('id desc')
                ->count();

            $list = $this->model
                ->where($where)
                //->where('id', 'in', $this->childrenAdminIds)
                ->field(['password', 'salt', 'token'], true)
                ->order('id desc')
                ->limit(0, 5)
                ->select();
            $result = array("total" => $total, "rows" => $list);

            return json($result);

        }
        return $this->view->fetch();
    }

    /**
     * 设计师列表
     * @return \think\response\Json|void
     */

    public function index2()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags']);
        $list=null;
        if ($this->request->isGet()) {
            $factoryid=$this->auth->id;

            $where=['factoryid'=>$factoryid];

            $total = $this->model
                ->where($where)
                ->order('id desc')
                ->count();

            $list = $this->model
                ->where($where)
                ->order('id desc')
                ->limit(0, 5)
                ->select();

            $list = collection($list)->toArray();
            $result = array("total" => $total, "rows" => $list);
        }
        $this->assign('designers',$list);
        return $this->view->fetch();
    }

    /**
     * 设计师添加
     */

    public function add()
    {
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                $admin=new Admin();
                $salt=Random::alnum();

                $data=[
                    'username'=>$params['username'],
                    'email'=>$params['email'],
                    'nickname'=>$params['nickname'],
                    'password'=>md5(md5($params['password']) . $salt),//$a->getEncryptPassword($params['password'],$salt),
                    'salt'=>$salt,
                    'status'=>$params['status'],
                    'createtime'=>time(),
                    'avatar'=>'/assets/img/avatar.png',
                    'updatetime'=>time(),
                    'factoryid'=>$this->auth->id
                ];

                if($admin->data($data)->save() && db('auth_group_access')->data(['uid'=>$admin->id,'group_id'=>$params['group']])->insert()){
                    $this->success('成功添加了一个设计师');
                }else{
                    $this->error('添加设计师失败');
                }
            }
            $this->error(__('参数 %s 不能为空', ''));
        }
        return $this->view->fetch();
    }


    //编辑
    public function edit($ids = null)
    {
        $admin=db('admin')->where('id','=',$ids)->find();
        //print_r($admin);die;
        if ($this->request->isPost()) {
            $this->token();
            $params = $this->request->post("row/a");
            //print_r($params);die;
            if ($params) {
                if ($params['password']) {
                    if (!Validate::is($params['password'], '\S{6,16}')) {
                        $this->error(__("Please input correct password"));
                    }
                    $params['salt'] = Random::alnum();
                    $params['password'] = md5(md5($params['password']) . $params['salt']);
                } else {
                    unset($params['password'], $params['salt']);
                }
                //这里需要针对username和email做唯一验证
                $adminValidate = \think\Loader::validate('Admin');
                $adminValidate->rule([
                    'username' => 'require|regex:\w{3,12}|unique:admin,username,' . $admin['id'],
                    'email'    => 'require|email|unique:admin,email,' . $admin['id'],
                    'password' => 'regex:\S{32}',
                ]);
                if ($adminValidate->check($params)){
                    db('admin')->where('id','=',$ids)->data($params)->update();
                    $this->success();
                }else{
                    $this->error($adminValidate->getError());
                }

            }
            $this->error();
        }
        $this->view->assign("admin", $admin);
        return $this->view->fetch();
    }

}